import React from "react";

import './login.css';
import UcnavBar from "../../components/uc-navBar/uc-navBar";
import { Link } from 'react-router-dom'
import UcInput from "../../components/uc-input/index";
import UcButton from "../../components/uc-button/uc-button";
import { queryLogin } from "../../services/user";
import qs from 'qs';


export default class Login extends React.Component {


  state = {
    username: '',
    password: '',
    mess: '',//错误信息
  };

  checkIpt = ev => this.setState({ [ev.target.name]: ev.target.value });

  login = async () => {
    let { username, password } = this.state;
    let res = await queryLogin({ username, password });
    // console.log(res)
    if (res.err === 0) {
      //成功 写token到本地,跳转到之前||user
      console.log('login', 1);
      window.localStorage.setItem('user', qs.stringify(res));
      if (this.props.location.search && !this.props.location.search.includes('/login')) {
        console.log('login', 2, this.props.location.search);
        this.props.history.push(this.props.location.search.substring(1))
      } else {
        console.log('login', 3);
        this.props.history.push('/user')
      }
    } else {
      //失败 写mess数据
      this.setState({ mess: res.msg })
    }


  };

  async componentDidMount() {

  }

  render() {
    let { username, password, mess } = this.state;
    return (
      <div className="content">
        <UcnavBar
          onLeftClick={() => this.props.history.go(-1)}
          icon={<img alt="arrow" src={require('../../assets/img/history1.png').default} />}
        />
        <h1 style={{ textAlign: 'center', lineHeight: '70px' }}>登录</h1>
        <div className="login-box">
          <p className="lsolid"></p>
          <div className="login">
            <Link to="/login">登录</Link>
            <span></span>
            <Link to="/reg">注册</Link>
          </div>
          <p className="rsolid"></p>
        </div>
        <ul>
          <UcInput
            label="账号"
            model={{ name: "username", value: username, onChange: this.checkIpt }}
          />
          <UcInput
            label="密码"
            type="password"
            model={{ name: "password", value: password, onChange: this.checkIpt }}
          />
          {mess}
        </ul>
        <div className="footbox" style={{ marginTop: '0.5rem' }}>
          <UcButton size="large" onClick={this.login}>登录</UcButton>
          <a href="#section" className="tishi">忘记密码？</a>
        </div>
      </div>

    );
  }
}
